import { BaseService } from '@/base/base.service'
import { BadRequestException, Injectable } from '@nestjs/common'
import { AdminUser } from '@prisma/client'
import { AdminUserDto } from './dto/admin-user.dto'
import { PrismaBaseService } from '@/prisma-base/prisma-base.service'
import { JwtService } from '@nestjs/jwt'
import { ConfigService } from '@nestjs/config'
import { AdminLoginDto } from './dto/login.dto'
import { hash, verify } from 'argon2'

@Injectable()
export class AdminUserService extends BaseService<AdminUser, AdminUserDto> {
  constructor(
    private readonly prismaBase: PrismaBaseService,
    private readonly jwt: JwtService,
    private readonly config: ConfigService,
  ) {
    super('AdminUser')
  }

  //后台登录
  async login(dto: AdminLoginDto) {
    const user = await this.prismaBase.adminUser.findUnique({
      where: {
        user_name: dto.user_name,
      },
    })
    if (!(await verify(user.password, dto.password))) {
      throw new Error('密码错误')
    }
    return await this.token(user)
  }

  async changePass(id: string, old_pass: string, new_pass: string) {
    const user = await this.prismaBase.adminUser.findUnique({
      where: {
        id,
      },
    })
    if (!(await verify(user.password, old_pass))) {
      throw new Error('原密码错误')
    }
    await this.prismaBase.adminUser.update({
      where: {
        id,
      },
      data: {
        password: await hash(new_pass),
      },
    })
  }

  private async token(argUser: AdminUser) {
    const { nick_name, user_name, id } = argUser
    const user = {
      id,
      nick_name,
      user_name,
    }
    return {
      user,
      token: await this.jwt.signAsync(
        {
          user_name,
          sub: id,
        },
        {
          secret: this.config.get('TOKEN_SECRET'),
        },
      ),
    }
  }
}
